package com.cater.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cater.annotation.SystemControllerLog;
import com.cater.common.PageResult;
import com.cater.query.CommonQuery;
import com.cater.sys.entity.Area;
import com.cater.sys.service.impl.AreaServiceImpl;
import com.cater.utils.TreeObject;
import com.cater.utils.TreeUtil;
import com.cater.utils.ZtreeObject;
import com.cater.utils.ZtreeUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @author 作者: sd
 * @date 创建时间：2017年2月28日 下午4:39:20
 * @version 1.0
 */
@Controller
@RequestMapping("/area")
public class AreaController {
	@Autowired
	private AreaServiceImpl service;

	@RequestMapping("/list")
	private String list() {
		return "sys/area/list";
	}

	@ResponseBody
	@RequestMapping(value = "/getAreaBypid")
	@SystemControllerLog(description = "区域树形展示")
	public JSONObject getAreaBypid(String nodeid, CommonQuery query) {
		JSONObject json = new JSONObject();
		if (StringUtils.isEmpty(nodeid)) {
			nodeid = "0";
		}
		TreeObject[] rows = TreeUtil.getAreaObjects(service.getByPid(nodeid, query));
		json.put("rows", rows);
		return json;
	}

	@RequestMapping("/listData")
	@ResponseBody
	@SystemControllerLog(description = "查看区域")
	public PageResult<Area> getAll(CommonQuery query, HttpServletRequest request) {
		PageResult<Area> result = service.findPageResult(query);
		return result;
	}

	/**
	 * 添加视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addView")
	@RequiresPermissions("area:add")
	public String addView(Model model, Integer fatherId, Integer level, CommonQuery query) {
		model.addAttribute("fatherId", fatherId);
		model.addAttribute("level", level);
		return "sys/area/add";
	}

	/**
	 * 添加操作
	 * 
	 * @param area
	 * @return
	 */
	@RequestMapping(value = "add")
	@RequiresPermissions("area:add")
	@ResponseBody
	@SystemControllerLog(description = "添加区域")
	public JSONObject add(Area area, CommonQuery query) {
		JSONObject json = new JSONObject();
		if (area.getFatherId() == 0) {
			area.setParentIds(area.getFatherId() + "");
			area.setTreeNames(area.getTitle());
		} else {
			query.setPid(String.valueOf(area.getFatherId()));
			Area fArea = service.getByParent(query);
			area.setParentIds(fArea.getParentIds() + "," + area.getFatherId());
			area.setTreeNames(fArea.getTreeNames() + "/" + area.getTitle());
		}
		int id = service.save(area);
		if (id != 0) {
			json.put("code", 200);
			json.put("message", "success");
		} else {
			json.put("code", 999);
			json.put("message", "fail");
		}
		return json;
	}

	/**
	 * 修改视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editView")
	@RequiresPermissions("area:update")
	public String editView(String id, Model model, CommonQuery query) {
		Area area = service.getById(id);
		model.addAttribute("area", area);
		return "sys/area/update";
	}

	/**
	 * 修改操作
	 * 
	 * @param area
	 * @return
	 */
	@RequestMapping(value = "update")
	@RequiresPermissions("area:update")
	@ResponseBody
	@SystemControllerLog(description = "修改区域")
	public JSONObject update(Area area, CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			if (area.getFatherId() == 0) {
				area.setParentIds(area.getFatherId() + "");
				area.setTreeNames(area.getTitle());
			} else {
				query.setPid(String.valueOf(area.getFatherId()));
				Area fArea = service.getByParent(query);
				area.setParentIds(fArea.getParentIds() + "," + area.getFatherId());
				area.setTreeNames(fArea.getTreeNames() + "/" + area.getTitle());
			}
			service.update(area);
			json.put("code", 200);
			json.put("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "修改失败");
		}
		return json;
	}

	/**
	 * 删除操作
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@SystemControllerLog(description = "删除区域")
	public JSONObject delete(String id) {
		JSONObject json = new JSONObject();
		try {
			int count = service.getChildCount(id);
			if (count > 0) {
				json.put("code", 400);
				json.put("message", "该区域存在子区域，不允许删除！");
			} else {
				service.delete(id);
				json.put("code", 200);
				json.put("message", "删除成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除失败");
		}
		return json;
	}

	@SuppressWarnings("null")
	@ResponseBody
	@RequestMapping("/treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) Integer extId,
			@RequestParam(required = false) String type, @RequestParam(required = false) Long grade,
			@RequestParam(required = false) Boolean isAll, HttpServletResponse response, CommonQuery query) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Area> list = service.getAllCommon(query);
		for (int i = 0; i < list.size(); i++) {
			Area e = list.get(i);
			if (extId != null || !extId.equals(e.getId())) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getFatherId());
				map.put("pIds", e.getFatherId());
				map.put("name", e.getTitle());
				if (type != null && "3".equals(type)) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;

	}

	@RequestMapping("/ztreeData")
	@ResponseBody
	public JSONObject getZtree(CommonQuery query) {
		JSONObject json = new JSONObject();
		ZtreeUtil ztreeUtil = new ZtreeUtil();
		ZtreeObject[] rows = ztreeUtil.getTreeObjects(service.getAll());
		json.put("rows", rows);
		return json;

	}

	/**
	 * ztree树形页面
	 */
	@RequestMapping(value = "/openZtree")
	public String openauth(HttpServletRequest request, Model model) {
		String ids = request.getParameter("ids");
		String pid = request.getParameter("pid");
		if (StringUtils.isNotBlank(ids)) {
			model.addAttribute("ids", ids);
		}
		if (StringUtils.isNotBlank(pid)) {
			model.addAttribute("pid", pid);
		}
		String tops = request.getParameter("tops");
		if (StringUtils.isNotBlank(tops)) {
			model.addAttribute("tops", tops);
		}
		return "sys/area/select_area";
	}

	/**
	 * 树形数据json
	 */
	@ResponseBody
	@RequestMapping(value = "/getZtreeJson")
	public List<Map<String, Object>> getZtreeJson(CommonQuery query,HttpServletRequest request) {
		String tempids = request.getParameter("ids");
		String[] ids = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		List<Area> areas = service.getAllList(query);
		if (StringUtils.isNotBlank(tempids) && !tempids.equals("undefined")) {
			ids = tempids.split(",");
		}
		for (Area t : areas) {
			map = new HashMap<String, Object>();
			map.put("id", t.getId());
			map.put("pId", t.getFatherId());
			map.put("name", t.getTitle());
			map.put("open", true);
			map.put("level", t.getLevel());
			if (ids != null) {
				for (int i = 0; i < ids.length; i++) {
					if (t.getId() == Integer.valueOf(ids[i])) {
						map.put("checked", true);
					}
				}
			}
			list.add(map);
		}
		return list;
	}

	/**
	 * 
	 * @Description:根据等级及id查询
	 * @param query
	 * @return List<Map<String,Object>>
	 * @time:2018年4月15日 下午9:42:55
	 */
	@ResponseBody
	@RequestMapping("getAreaJson")
	public List<Map<String, Object>> getLevelAll(CommonQuery query) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		try {
			List<Area> areas = service.getByLevelAll(query);
			for (Area area : areas) {
				map = new HashMap<String, Object>();
				map.put("id", area.getId());
				map.put("pid", area.getFatherId());
				map.put("name", area.getTitle());
				map.put("level", area.getLevel());
				if (StringUtils.isNotEmpty(query.getId())) {
					if (area.getId() == Integer.valueOf(query.getId())) {
						map.put("selected", "selected");
					}
				}
				list.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@ResponseBody
	@RequestMapping("addAll")
	public String addAll() {
		List<Map<String, Object>> list = service.getOtherAll();
		Area area = null;
		Integer codep = null;
		Integer codec = null;
		for (Map<String, Object> map : list) {
			area = new Area();
			area.setLevelCode(String.valueOf(map.get("code_p")));
			codep = Integer.valueOf(area.getLevelCode());
			area.setLevel(1);
			area.setFatherId(0);
			area.setParentIds("0");
			area.setTitle(String.valueOf(map.get("name")));
			area.setTreeNames(String.valueOf(map.get("name")));
			Integer pid = service.save(area);
			if (pid > 0) {
				List<Map<String, Object>> cityList = service.getCityAll(codep);
				for (Map<String, Object> mapc : cityList) {
					area = new Area();
					area.setLevelCode(String.valueOf(mapc.get("code_c")));
					codec =Integer.valueOf(area.getLevelCode());
					area.setLevel(2);
					area.setFatherId(pid);
					area.setParentIds("0" + "," + pid);
					area.setTitle(String.valueOf(mapc.get("name")));
					area.setTreeNames(String.valueOf(map.get("name")) + "/" + String.valueOf(mapc.get("name")));
					Integer cid = service.save(area);
					if (cid > 0) {
						List<Map<String, Object>> areaList = service.getAreaAll(codec);
						for (Map<String, Object> mapa : areaList) {
							area = new Area();
							area.setLevelCode(String.valueOf(mapa.get("code_a")));
							area.setLevel(3);
							area.setFatherId(cid);
							area.setParentIds("0" + "," + pid+","+cid);
							area.setTitle(String.valueOf(mapa.get("name")));
							area.setTreeNames(String.valueOf(map.get("name")) + "/" + String.valueOf(mapc.get("name"))+"/"+String.valueOf(mapa.get("name")));
							service.save(area);
						}
					}
				}
			}
		}
		return "ok";

	}
}
